;(function () {
  new Vue({
    el: '#JYprint',
    data: {
      data: [],
      projectData: {
        companyName: '',
        name: '',
        date:'',
        bankAccounts: ''
      },
      num: 0,
      contractData: [],
      billData:[],
      units:null,
      amountData: {
        expenses: []
      },
      today:null,
      deadlineYear:null,
      deadlineMonth:null,
      deadlineDay:null,
      rentPriceUnit:'D'
    },
    filters: {
      formatNum:function(num){
        return hlNumberUtil.formatNum(num)
      },
      dateCover: function (time) {
        return hlDateUtil.formatUTCDate(time,'yyyy-MM-dd')
      },
      toFixed2: function (n) {
        return hlNumberUtil.formatNum(Number(n).toFixed(2))
      }
    },
    computed: {
      total: function () {
        var result = 0;
        this.amountData.expenses.map(function(item) {
          result+=item.amountTPay
        })
        return result
      }
    },
    methods: {
      curDate:function(){
        this.today = hlDateUtil.formatDate(new Date(),'yyyy-MM-dd')
      },
      //联动银行
      linkBank: function (i) {
        this.num = i;
      },
      //获取项目
      getProjectMes: function () {
        var projectId = window.localStorage.getItem('PROJECTID');
        var _this = this;
        hlhttp.get({
          url: 'project',
          data: {project_id:projectId},
          success: function (res) {
            _this.projectData = {
              companyName: res.pcompany,
              name: res.name,
              bankAccounts: res.bankAccounts ? res.bankAccounts.split(',') : null,
              bankName: res.bankNames ? res.bankNames.split(',') : null,
              accountNames: res.accountNames ? res.accountNames.split(',') : null,
              date: hlDateUtil.formatUTCDate(new Date().getTime(),'yyyy-MM-dd'),
              legalName: res.legalName,
              addrees: res.provinceName+' '+res.cityName+ ' ' + res.districtName+' '+res.address,
              rpersonPhone: res.rpersonPhone,
              rpersonName: res.rpersonName
            }
          }
        })
      },
      //获取合同信息
      getContractMes: function () {
        var id = hlUrlUtil.GetQueryString('aid');
        var self = this;
        hlhttp.get({
          url: 'contract',
          data: {id:id},
          success: function (res) {
            self.rentPriceUnit = res.rentPriceUnit;
            self.contractData = {
              mCode:res.mCode,
              projectName:res.projectName,
              units: res.units,
              zlfCompany: res.zlfCompany,
              acreage: res.rentAcreage,
              rentPrice: res.rentPrice
            }

            for (var i = 0; i <  self.amountData.expenses.length; i++) {
              for (var j = 0; j < res.expenses.length; j++) {
                if (self.amountData.expenses[i].name === res.expenses[j].expenseName) {
                  self.amountData.expenses[i].expense = res.expenses[j].expense
                }
              }
            }

            // 调整单元的数据
            var unitsArr = [];
            res.units.map(function(_item){
              var obj = {}
              if(_item.positions.length == 0){
                obj = {
                  'buildingName':_item.buildingName,
                  'floorNum':_item.floorNum,
                  'unitName':_item.unitName,
                  'positionName':''
                }
                unitsArr.push(obj)
              }
              if(_item.positions.length){
                // 工位类型
                if(_item.unitType === 'WP'){
                  obj = {
                    'buildingName':_item.buildingName,
                    'floorNum':_item.floorNum,
                    'unitName':_item.unitName,
                    'positionName':'工位' + _item.positions.length + '个'
                  }
                  unitsArr.push(obj)
                }
                // 车位类型
                if(_item.unitType === 'ST'){
                  obj = {
                    'buildingName':_item.buildingName,
                    'floorNum':_item.floorNum,
                    'unitName':_item.unitName,
                    'positionName':'车位' + _item.positions.length + '个'
                  }
                  unitsArr.push(obj)
                }
              }
            })
            self.units = unitsArr
          }
        })
      },
      //获取缴费信息
      getAccountsMes: function () {
        var id = hlUrlUtil.GetQueryString('id');
        var _this = this;
        hlhttp.get({
          url: 'bill,expenses,transactions',
          data: {bill_id: id},
          success: function (res) {
            _this.billData = res;
            var deadlineDate = hlDateUtil.formatUTCDate(res.deadlineDate,'yyyy-MM-dd');
            _this.deadlineYear = deadlineDate.substr(0,4)
            _this.deadlineMonth = deadlineDate.substr(5,2)
            _this.deadlineDay = deadlineDate.substr(8,2)

            _this.amountData = {
              endDate: hlDateUtil.formatUTCDate(res.deadlineDate,'yyyy-MM-dd'),
              expenses: res.expenses,
              beginTime: res.beginDate,
              endTime: res.endDate
            }
            // 费项数据
            _this.getContractMes()
          }
        })
      },
      //打印
      print: function () {
        $(document).on('click', '.js-print', function(event) {
          var bdhtml=window.document.body.innerHTML;
          var prnhtml = $('.pt-wrap').html()
          window.document.body.innerHTML=prnhtml;
          window.print();
          window.document.body.innerHTML=bdhtml;
        });
      },
      // 导出PDF
      exportPDF:function(){
        $(document).on('click', '.export-pdf', function(event) {
          html2canvas(document.querySelector('.pt-wrap'),{
            scale: 1,
            background: "#fff",
            onrendered:function(canvas){

              var contentWidth = canvas.width;
              var contentHeight = canvas.height;

              // 一页pdf显示html页面生成的canvas高度;
              var pageHeight = contentWidth / 595.28 * 841.89;
              // 未生成pdf的html页面高度
              var leftHeight = contentHeight
              // 页面偏移
              var position = 0;
              // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
              var imgWidth = 595.28;
              var imgHeight = 595.28/contentWidth * contentHeight

              var imgData = canvas.toDataURL('image/jpeg',1.0);
              //初始化pdf，设置相应格式（单位为pt,导出a4纸的大小）
              var doc = new jsPDF("p", "pt", "a4");

              if(leftHeight < pageHeight){
                doc.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);
              }else{
                while(leftHeight > 0) {
                  doc.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight)
                  leftHeight -= pageHeight;
                  position -= 841.89;
                  //避免添加空白页
                  if(leftHeight > 0) {
                    doc.addPage();
                  }
                }
              }
              //输出保存命名为bill的pdf
              doc.save('bill.pdf');
            }
          })
        })

      },
    },
    mounted: function () {
      hlSelectUi()
      this.curDate()
      this.getProjectMes()
      this.getAccountsMes()
      this.print()
    }
  })
}())
